//
//  CNPhotoSeletorCell.swift
//  PhotoSeletor
//
//  Created by 陈锦聪 on 16/4/3.
//  Copyright © 2016年 Coco. All rights reserved.
//

import UIKit

protocol CNPhotoSeletorCellDelegate: NSObjectProtocol {
    func photoSeletorCellDidClickAddButton(cell: CNPhotoSeletorCell)
    func photoSeletorCellDidClickDeleteButton(cell: CNPhotoSeletorCell)
}

class CNPhotoSeletorCell: UICollectionViewCell {
    
    var image: UIImage? {
        didSet {
            addButton.setImage(image, forState: UIControlState.Normal)
            deleteButton.hidden = false
        }
    }    
    weak var delegate: CNPhotoSeletorCellDelegate?
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }
    private func prepareUI() {
        contentView.addSubview(addButton)
        contentView.addSubview(deleteButton)
        addButton.translatesAutoresizingMaskIntoConstraints = false
        deleteButton.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["ab" : addButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["ab" : addButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[db]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["db" : deleteButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[db]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["db" : deleteButton]))
    }
    @objc private func addButtonAction() {
        delegate?.photoSeletorCellDidClickAddButton(self)
    }
    @objc private func deleteButtonAction() {
        delegate?.photoSeletorCellDidClickDeleteButton(self)
    }
    /// 重置添加按钮
    func resetAddButton() {
        addButton.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        deleteButton.hidden = true
    }
    // MARK: - 懒加载
    private lazy var addButton: UIButton = {
        let button = UIButton()
        button.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
        button.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        button.addTarget(self, action: "addButtonAction", forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        button.addTarget(self, action: "deleteButtonAction", forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
}
